package nl.walnut.ileftyousomecheddar;

import java.io.File;
import java.io.IOException;
import java.util.Random;


import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.os.StrictMode;
//import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
//import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


public class WriteCheeseActivity extends Activity {

	final Context context = this;
	
		@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.write_cheese_activity);
	        Button bt= (Button) findViewById(R.id.Done);
	        bt.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
				
					try{postDigitalNote();}
					catch(Exception e){showPopup(e.toString());}
					//new Connection().execute();
					
				}
	        });
	    	         	        
		}
		
		private Location getLocation() throws Exception {
			LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if(location == null){
				location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
			}
			if(location == null){
				throw new Exception("can not aquire location");
			}
			return location;
		}

		public void showPopup(String message){
			// custom dialog
						final Dialog dialog = new Dialog(context);
						dialog.setContentView(R.layout.dialog);
						dialog.setTitle(message);
			 
						// set the custom dialog components - text, image and button
						TextView text = (TextView) dialog.findViewById(R.id.text);
						text.setText(message);
						Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
						// if button is clicked, close the custom dialog
						dialogButton.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog.dismiss();
								finish();
							}
						});
			 
						dialog.show();
		}

		/*private class Connection extends AsyncTask{
			 
	        @Override
	        protected Object doInBackground(Object...objects) {
	        	try{postDigitalNote();}
				catch(Exception e){showPopup(e.toString());}
	            return null;
	        }
	 
	    }*/
		
		private final String HOST = "http://digital-notes.appspot.com";

        public void postDigitalNote() throws ClientProtocolException, IOException{

            //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            //StrictMode.setThreadPolicy(policy);

        	
        	// first retrieve upload url
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(HOST + "/upload");
                HttpResponse urlResponse = httpClient.execute(httpGet);
                String uploadUrl = EntityUtils.toString(urlResponse.getEntity());

                // get the image from the sdcard
                //File image = new File("test"); 
                //TODO:  check correct implementation to get file
                
                Location location = null;
                try {
                	location = getLocation();
				} catch (Exception e) {
					e.printStackTrace();
				}

                // create the request object
                MultipartEntity digitalNote = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                //digitalNote.addPart("image",new FileBody(image, "multipart/form-data"));
                EditText etxt = (EditText) findViewById(R.id.CheeseTitle);
                String txt = etxt.getText().toString();
                digitalNote.addPart("title",new StringBody(txt));
                etxt = (EditText) findViewById(R.id.CheeseText);
                txt = etxt.getText().toString();
                digitalNote.addPart("text",new StringBody(txt));
                digitalNote.addPart("latitude",new StringBody("" + location.getLatitude()));
                digitalNote.addPart("longitude",new StringBody("" + location.getLongitude()));

                
                // send the request
                HttpPost httpPost = new HttpPost(uploadUrl);
                httpPost.setEntity(digitalNote);
                HttpResponse response = httpClient.execute(httpPost);
                 
                // check status of response
                if(response.getStatusLine().getStatusCode() == 201 ){
                	showPopup("Let's hope someone will take it!");    
                }else{
                	/*Toast.makeText(WriteCheeseActivity.this,
                			response.getStatusLine().getStatusCode(),
    	                    Toast.LENGTH_LONG).show();*/
                	showPopup(Integer.toString(response.getStatusLine().getStatusCode()));
                }
        }
		
}